package bicing;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import storage.KMLDocument;

@SuppressWarnings("serial")
public class CronServlet extends HttpServlet {
	private final Logger logger = Logger.getLogger(this.getClass().getPackage().getName());
	private Parser parser;
	private final static PersistenceManager persistenceManager = PersistenceManagerSingleton.getPersistenceManager();

	@Override
	public final void init() throws ServletException {
		try {
			parser = new Parser();
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
		resp.setContentType("text/plain");
		try{
			String kml = parser.getKML();
			if(kml != null){
				KMLDocument kmlDocument = new KMLDocument(kml);
				persistenceManager.makePersistent(kmlDocument);
				resp.getWriter().write("KML updated");
				logger.info("KML updated");
			}else{
				resp.getWriter().write("Failed to update KML");
				logger.info("Failed to update KML");
			}
		}catch(Exception e){
			throw new ServletException(e);
		}
	}
}
